package com.gzx.plugin.tjzy.modular.sms.record.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.gzx.plugin.tjzy.modular.sms.record.entity.GzxSmsRecord;
import com.gzx.plugin.tjzy.modular.sms.record.mapper.GzxSmsRecordMapper;
import com.gzx.plugin.tjzy.modular.sms.record.service.GzxSmsRecordService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import vip.xiaonuo.common.consts.IntConstant;
import vip.xiaonuo.common.util.CommonDateUtil;
import vip.xiaonuo.common.util.CommonSleepUtil;

import java.util.List;
import java.util.stream.Collectors;

import static org.apache.commons.lang.StringEscapeUtils.escapeSql;

/**
 * @author zjt
 * @description
 * @date 2025/3/26 11:10
 */
@Service
@RequiredArgsConstructor
public class GzxSmsRecordServiceImpl implements GzxSmsRecordService {

    private final GzxSmsRecordMapper smsRecordMapper;

    /**
     * 批量新增
     *
     * @param smsRecordList
     */
    @Override
    @DS("sms")
    public void insertBatch(List<GzxSmsRecord> smsRecordList) {
        List<List<GzxSmsRecord>> bacthList = Lists.partition(smsRecordList, IntConstant.VALUE_1000);
        for (List<GzxSmsRecord> smsRecordBatch : bacthList) {
            String batchSql = smsRecordBatch.stream()
                    .map(s -> String.format("('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
                            escapeSql(String.valueOf(s.getSendType())),
                            escapeSql(s.getSupplierOrder()),
                            escapeSql(s.getSupplierCode()),
                            escapeSql(s.getProjectCode()),
                            escapeSql(s.getBatchNumber()),
                            escapeSql(s.getPhone()),
                            escapeSql(s.getMsgId()),
                            escapeSql(s.getContent()),
                            escapeSql(s.getCreateUser()),
                            escapeSql(CommonDateUtil.dateTimeToStr(s.getCreateTime())),
                            escapeSql(s.getTenantId())
                    ))
                    .collect(Collectors.joining(", ")).replace("'null'", "null");
            smsRecordMapper.insertBatchByValSql(batchSql);
            CommonSleepUtil.sleep(IntConstant.VALUE_100);
        }
    }

    /**
     * 查询短信发送记录
     *
     * @param lambdaQueryWrapper
     * @return
     */
    @Override
    @DS("sms")
    public List<GzxSmsRecord> listByWrapper(LambdaQueryWrapper<GzxSmsRecord> lambdaQueryWrapper) {
        return smsRecordMapper.selectList(lambdaQueryWrapper);
    }
}
